﻿aSettings = CreateFrame("Frame", "aSettings", UIParent)
aSettings:SetScript("OnEvent", function(self, event, ...) self[event](self, event, ...) end)
aSettings:RegisterEvent("PLAYER_DEAD")
aSettings:RegisterEvent("ADDON_LOADED")
aSettings:RegisterEvent("PLAYER_LOGIN")
aSettings:RegisterEvent("MERCHANT_SHOW")
aSettings:RegisterEvent("DUEL_REQUESTED")
aSettings:RegisterEvent("START_LOOT_ROLL")
aSettings:RegisterEvent("PARTY_INVITE_REQUEST")
aSettings:RegisterEvent("CONFIRM_DISENCHANT_ROLL")
aSettings:RegisterEvent("LOOT_BIND_CONFIRM")
aSettings:RegisterEvent("CONFIRM_LOOT_ROLL")

local defaults = {
	AutoGreedOnGreen = false,
	AutoRepair = true,
	UseGuildBank = true,
	SellGreyCrap = true,
	DeclineDuels = true,
	AcceptInvites = false,
	NoErrors = true,
	UIScale = false,
	AutoRez = false,
	nnCastSpam = false,
}

--[[ Loading ]]
function aSettings:ADDON_LOADED(event, addon)
	if(addon~="aSettings") then return end

	aSettingsDB = setmetatable(aSettingsDB or {}, {__index = defaults})

	CreateFrame("Frame", nil, InterfaceOptionsFrame):SetScript("OnShow", function()
	if(not IsAddOnLoaded("aSettings_Config")) then LoadAddOn("aSettings_Config") end
	self:SetScript("OnShow", nil)
	end)

	SLASH_ASETTINGS1 = "/asettings"
	SLASH_ASETTINGS2 = "/aset"
	SlashCmdList["ASETTINGS"] = function()
	if(not IsAddOnLoaded("aSettings_Config")) then LoadAddOn("aSettings_Config") end
	InterfaceOptionsFrame_OpenToCategory("aSettings")
	end

	if(aSettingsDB.NoErrors==true) then UIErrorsFrame:UnregisterEvent("UI_ERROR_MESSAGE") end

	SetCVar("CameraDistanceMax", 50)
	SetCVar("CameraDistanceMaxFactor", 3.4)

	self:UnregisterEvent(event)
end

--[[ Creating info text ]]
local frame = CreateFrame("Frame", nil, UIParent)
frame:SetScript("OnUpdate", FadingFrame_OnUpdate)
frame.fadeInTime = 0.5
frame.fadeOutTime = 2
frame.holdTime = 3
frame:Hide()

local text = frame:CreateFontString("aInfoText", "OVERLAY")
text:SetFont(STANDARD_TEXT_FONT, 32, "THICKOUTLINE")
text:SetPoint("CENTER", UIParent, 0, 200)
text:SetTextColor(0.41, 0.8, 0.94)

aInfoText_ShowText = function(s)
	text:SetText(s)
	FadingFrame_Show(frame)
end

function aSettings:CONFIRM_DISENCHANT_ROLL(event, id, typ)
	if(not aSettingsDB.AutoGreedOnGreen) then return end
	GetLootRollItemInfo(id)
	GetLootRollItemInfo(id)
	ConfirmLootRoll(id,typ)
end

function aSettings:LOOT_BIND_CONFIRM(event, id)
	if(not aSettingsDB.AutoGreedOnGreen) then return end
	StaticPopup_Hide("LOOT_BIND")
	ConfirmLootSlot(id)
end

function aSettings:CONFIRM_LOOT_ROLL(event, id, rollType)
	if(not aSettingsDB.AutoGreedOnGreen) then return end
	StaticPopup_Hide(event)
	ConfirmLootRoll(id,rollType)
end

--[[ 차비 굴리기 ]]
function aSettings:START_LOOT_ROLL(event, id, item)
	--[[Roll Type:  0 = 포기 | 1 = 입찰 | 2 = 차비 | 3 = 마부]]--
	--[[Quality Type: 0 = 하급 | 1 = 일반 | 2 = 고급 | 3 = 희귀 | 4 = 영웅 | 5 = 전설 | 6 = 유물 | 7 = 계승 ]]--
	if(not aSettingsDB.AutoGreedOnGreen) then return end

	local _, name, _, quality, bindOnPickUp, canNeed, canGreed, canDisenchant = GetLootRollItemInfo(id);
	if id and (name == "마모된 칼자루" or name == "문양 숙련의 서적" or name == "소용돌이 수정" or name == "동전 가방") then
		RollOnLoot(id, 1)
		return
	elseif id and (name == "혼돈의 보주" or name == "얼어붙은 보주" or name == "성전사 보주") then
		RollOnLoot(id, 2)
		return
	elseif id and (UnitLevel("player") == 85) and (select(4, GetLootRollItemInfo(id)) == 2) and not (select(5, GetLootRollItemInfo(id))) then
		RollOnLoot(id, 3)
		if not RollOnLoot(id, 3) then
			RollOnLoot(id, 2)
		end
	end
end

--[[ 수리 & 잡템 판매 ]]
function aSettings:MERCHANT_SHOW()
	if(aSettingsDB.AutoRepair==true and CanMerchantRepair()) then
		local cost = GetRepairAllCost()
		if(not cost or cost==0) then return end

		local CanGuildRepair = aSettingsDB.UseGuildBank and IsInGuild() and CanGuildBankRepair() and GetGuildBankWithdrawMoney()>cost and GetGuildBankMoney()>cost
		if(CanGuildRepair) then
			RepairAllItems(1)
			aInfoText_ShowText(format("길드 은행 수리 비용: %.1f골드", cost * 0.0001))
		elseif(GetMoney()>cost) then
			RepairAllItems()
			aInfoText_ShowText(format("수리 비용: %.1f골드", cost * 0.0001))
		end
	end

	if(aSettingsDB.SellGreyCrap==true) then
		local bag, slot
		for bag = BACKPACK_CONTAINER, NUM_BAG_SLOTS do
			for slot = 1, GetContainerNumSlots(bag) do
				local link = GetContainerItemLink(bag, slot)
				if link and (select(3, GetItemInfo(link))==0) then
					UseContainerItem(bag, slot)
				end
			end
		end
	end
end

--[[ UIScale ]]
local Scales = {
	["768"] = 1,
	["800"] = 0.8,
	["864"] = 0.8,
	["900"] = 0.8,
	["960"] = 0.8,
	["1024"] = 0.65,
	["1050"] = 0.75,
	["1080"] = 0.75,
	["1200"] = 0.75,
}

function aSettings:PLAYER_LOGIN()
	if(not aSettingsDB.UIScale) then return end
	local _, height = string.match((({GetScreenResolutions()})[GetCurrentResolution()] or ""), "(%d+).-(%d+)")
	if(height and Scales[height]) then
		SetCVar("useUiScale", 1)
		SetCVar("uiScale", Scales[height])
	else
		SetCVar("useUiScale", 0)
		if(tonumber(height)>768) then
			print("Your resolution is not yet supported, disabling UI Scale.")
		end
	end
end

--[[ 자동 결투 거절 ]]
function aSettings:DUEL_REQUESTED(event, name)
	if(not aSettingsDB.DeclineDuels) then return end
	HideUIPanel(StaticPopup1)
	CancelDuel()
	aInfoText_ShowText("결투 요구 거절: "..name)
end

--[[ 자동 부활 ]]
function aSettings:PLAYER_DEAD()
	if(not aSettingsDB.AutoRez) then return end
	if(MiniMapBattlefieldFrame.status and MiniMapBattlefieldFrame.status=="active") then
		RepopMe()
	end
end

--[[ 초대 수락 ]]
local IsFriend = function(name)
	for i=1, GetNumFriends() do if(GetFriendInfo(i)==name) then return true end end
	if(IsInGuild()) then for i=1, GetNumGuildMembers() do if(GetGuildRosterInfo(i)==name) then return true end end end
end

function aSettings:PARTY_INVITE_REQUEST(event, name)
	if(not aSettingsDB.AcceptInvites) then return end
		if(IsFriend(name)) then
			aInfoText_ShowText("초대 수락: "..name)
			AcceptGroup()
			for i = 1, 4 do
			local frame = _G["StaticPopup"..i]
			if(frame:IsVisible() and frame.which=="PARTY_INVITE") then
			frame.inviteAccepted = 1
			StaticPopup_Hide("PARTY_INVITE")
			return
		end
	end
	else
		SendWho(name)
	end
end

--[[ nnCast 차단]]
function nnCastFilter(self, event, msg, player, ...)
	if(not aSettingsDB.nnCastSpam) then return end
	if not CanComplainChat(player) or UnitIsInMyGuild(player) then return end -- 자신/친구/길드원들은 필터링 하지 않음
	local badWords = {"->", "<-", "▶", "◀"}
	local matchCount = 0;
	for _, word in ipairs(badWords) do
		if (string.match(msg, word)) then
			matchCount = matchCount + 1;
		end
	end
	if (matchCount > 1) then
		return true;
	else
		return false;
	end
end
for _, event in pairs{"SAY", "YELL", "PARTY", "PARTY_LEADER", "RAID", "RAID_LEADER", "RAID_WARNING"} do ChatFrame_AddMessageEventFilter("CHAT_MSG_" ..event, nnCastFilter) end  -- "GUILD",
